package com.example;

import java.util.*;

/**
 * @Author loubobooo
 * @Description #148. 排序链表
 * @Date 2022/3/2
 */
public class SortList {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 方法描述:给你链表的头结点head，请将其按 升序 排列并返回 排序后的链表 。
     *
     * 示例 1：
     * 输入：head = [4,2,1,3]
     * 输出：[1,2,3,4]
     * @param: [head]
     * @return: com.example.SortList.ListNode
     * @author: loubobooo
     * @date: 2022/3/2
     */
    public ListNode sortList(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        ListNode listNode = new ListNode(-1);
        ListNode result = listNode;
        for (Integer i : list) {
            result.next = new ListNode(i);
            result = result.next;
        }
        return listNode.next;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{4,19,14,5,-3,1,8,5,11,15};
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            list.add(nums[i]);
        }
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        for (Integer i : list) {
            System.out.println(i);
        }
    }
}
